// 简单的内存缓存管理器
class SimpleCache {
  constructor() {
    this.cache = new Map();
    this.defaultTTL = 10 * 60 * 1000; // 10分钟，默认过期时间
  }

  /**
   * 生成缓存键
   * @param {string} key - 基础键名
   * @param {Object} params - 参数对象
   * @returns {string} 缓存键
   */
  generateKey(key, params = {}) {
    const sortedParams = Object.keys(params)
      .sort()
      .map(k => `${k}=${params[k]}`)
      .join('&');

    return sortedParams ? `${key}:${sortedParams}` : key;
  }

  /**
   * 设置缓存
   * @param {string} key - 缓存键
   * @param {any} data - 要缓存的数据
   * @param {number} ttl - 过期时间（毫秒），可选
   */
  set(key, data, ttl = this.defaultTTL) {
    const expiresAt = Date.now() + ttl;
    this.cache.set(key, {
      data,
      expiresAt,
      createdAt: Date.now()
    });

    console.log(`缓存设置: ${key} (过期时间: ${new Date(expiresAt).toLocaleTimeString()})`);
  }

  /**
   * 获取缓存
   * @param {string} key - 缓存键
   * @returns {any|null} 缓存的数据，如果过期或不存在则返回null
   */
  get(key) {
    const item = this.cache.get(key);

    if (!item) {
      console.log(`缓存未命中: ${key}`);
      return null;
    }

    if (Date.now() > item.expiresAt) {
      console.log(`缓存过期: ${key}`);
      this.cache.delete(key);
      return null;
    }

    console.log(`缓存命中: ${key} (剩余时间: ${Math.round((item.expiresAt - Date.now()) / 1000)}秒)`);
    return item.data;
  }

  /**
   * 删除缓存
   * @param {string} key - 缓存键
   */
  delete(key) {
    const deleted = this.cache.delete(key);
    if (deleted) {
      console.log(`缓存删除: ${key}`);
    }
    return deleted;
  }

  /**
   * 清空所有缓存
   */
  clear() {
    const size = this.cache.size;
    this.cache.clear();
    console.log(`清空缓存: 删除了${size}个缓存项`);
  }

  /**
   * 获取缓存统计信息
   * @returns {Object} 缓存统计
   */
  getStats() {
    const now = Date.now();
    let active = 0;
    let expired = 0;

    for (const [key, item] of this.cache) {
      if (now > item.expiresAt) {
        expired++;
      } else {
        active++;
      }
    }

    return {
      total: this.cache.size,
      active,
      expired,
      hitRate: this.hitCount > 0 ? (this.hitCount / (this.hitCount + this.missCount)) : 0
    };
  }

  /**
   * 清理过期缓存
   */
  cleanup() {
    const now = Date.now();
    const keysToDelete = [];

    for (const [key, item] of this.cache) {
      if (now > item.expiresAt) {
        keysToDelete.push(key);
      }
    }

    keysToDelete.forEach(key => this.cache.delete(key));

    if (keysToDelete.length > 0) {
      console.log(`清理过期缓存: 删除了${keysToDelete.length}个缓存项`);
    }

    return keysToDelete.length;
  }

  /**
   * 带缓存的请求方法
   * @param {string} key - 缓存键
   * @param {Function} fetcher - 获取数据的函数
   * @param {Object} params - 请求参数
   * @param {number} ttl - 缓存时间
   * @returns {Promise<any>} 缓存的数据或新获取的数据
   */
  async cachedRequest(key, fetcher, params = {}, ttl = this.defaultTTL) {
    const cacheKey = this.generateKey(key, params);

    // 尝试从缓存获取
    const cachedData = this.get(cacheKey);
    if (cachedData !== null) {
      return {
        data: cachedData,
        fromCache: true,
        cacheKey: cacheKey
      };
    }

    // 缓存未命中，执行请求
    try {
      console.log(`执行新请求: ${cacheKey}`);
      const data = await fetcher();

      // 缓存成功的结果
      this.set(cacheKey, data, ttl);

      return {
        data: data,
        fromCache: false,
        cacheKey: cacheKey
      };
    } catch (error) {
      console.error(`请求失败: ${cacheKey}`, error.message);
      throw error;
    }
  }
}

// 创建单例实例
const cache = new SimpleCache();

module.exports = cache;
